import type {QueryOptions, SharedQueryOptions} from '@/shared/types';
import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query';
import {usersService} from './usersService';
import {User, usersServiceKeys} from './domain';

export const usersOptions = (options?: QueryOptions<User[]>): SharedQueryOptions<User[]> => ({
    queryKey: usersServiceKeys.users(),
    queryFn: () => usersService.getUsers(),
    ...options,
});

export const useUsers = (options?: QueryOptions<User[]>) => {
    return useQuery(usersOptions(options));
};

export const useCreateUser = () => {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: (data: { name: string; email: string }) => usersService.createUser(data),
        onSuccess: () => {
            // Invalidate and refetch users
            queryClient.invalidateQueries({queryKey: usersServiceKeys.users()});
        },
    });
};

export const useUser = (id: number, options?: QueryOptions<User | undefined>) => {
    return useQuery({
        queryKey: [...usersServiceKeys.users(), id],
        queryFn: () => {
            // Don't fetch if id is not valid
            if (!id || id <= 0) {
                return Promise.resolve(undefined);
            }
            return usersService.getUserById(id);
        },
        ...options,
    });
};